package com.example.hospital.service;

import com.example.hospital.domain.entity.ExaminationIndicator;
import com.example.hospital.domain.entity.ExaminationOrder;
import com.example.hospital.domain.entity.PackageItem;
import com.example.hospital.domain.entity.Sample;
import com.example.hospital.mapper.ExaminationIndicatorMapper;
import com.example.hospital.mapper.ExaminationOrderMapper;
import com.example.hospital.mapper.PackageItemMapper;
import com.example.hospital.mapper.SampleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class OrderService {
    private final ExaminationOrderMapper orderMapper;
    private final PackageItemMapper packageItemMapper;
    private final ExaminationIndicatorMapper indicatorMapper;
    private final SampleMapper sampleMapper;

    public OrderService(ExaminationOrderMapper orderMapper,
                        PackageItemMapper packageItemMapper,
                        ExaminationIndicatorMapper indicatorMapper,
                        SampleMapper sampleMapper) {
        this.orderMapper = orderMapper;
        this.packageItemMapper = packageItemMapper;
        this.indicatorMapper = indicatorMapper;
        this.sampleMapper = sampleMapper;
    }
    /**
     * 更新订单状态并自动生成待采集样本
     * @param orderId
     * @param status
     * @param remark
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatusAndAutoSamples(Long orderId, Integer status, String remark) {
        boolean updated = orderMapper.updateStatus(orderId, status, remark) > 0;
        if (!updated) return false;
        if (status != null && status == 2) { // 已确认
            ExaminationOrder order = orderMapper.findById(orderId);
            if (order != null) {
                generatePendingSamplesIfNeeded(order);
            }
        }
        return true;
    }
    /**
     * 生成待采集样本（如果订单是套餐订单且包含指标）
     * @param order
     */
    private void generatePendingSamplesIfNeeded(ExaminationOrder order) {
        List<Long> indicatorIds = new ArrayList<>();
        if ("PACKAGE".equals(order.getOrderType()) && order.getPackageId() != null) {
            List<PackageItem> items = packageItemMapper.listByPackageId(order.getPackageId());
            for (PackageItem it : items) {
                if (it.getIndicatorId() != null) indicatorIds.add(it.getIndicatorId());
            }
        } else if ("INDICATOR".equals(order.getOrderType()) && order.getIndicatorId() != null) {
            indicatorIds.add(order.getIndicatorId());
        }
        // 按指标的specimenType聚合样本类型
        Set<String> specimenTypes = new HashSet<>();
        for (Long indId : indicatorIds) {
            ExaminationIndicator ind = indicatorMapper.findById(indId);
            String st = ind != null ? ind.getSpecimenType() : null;
            if (st != null && !st.isBlank()) specimenTypes.add(st.trim());
        }
        // 为每个样本类型创建一条待采集样本（避免重复）
        for (String type : specimenTypes) {
            if (!existsSample(order.getOrderId(), type)) {
                Sample s = new Sample();
                s.setOrderId(order.getOrderId());
                s.setSampleType(type);
                s.setCollectionTime(null);
                s.setStatus(1); // 1:正在采集/待采集
                s.setRemark("系统自动生成待采集样本");
                sampleMapper.insert(s);
            }
        }
    }
    /**
     * 检查订单是否已存在指定样本类型的样本
     * @param orderId
     * @param sampleType
     * @return
     */
    private boolean existsSample(Long orderId, String sampleType) {
        // 复用列表查询，判断是否已有同类型样本
        List<Sample> list = sampleMapper.list(null, orderId, sampleType, null, 1, 0);
        return list != null && !list.isEmpty();
    }
}